const router = require('express').Router();
const fs = require('fs');
const db = require("./public/db");
//获取分类管理数据
router.get('/Category', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql('select * from Category', (err, data) => {
        res.send(JSON.stringify(data));
    });
});
//添加分类管理数据
router.post('/add', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql(`insert into Category(Cover,Name) values('${req.query.coverUrl}','${req.query.Name}')`, (err, data) => {
        if (data.rowsAffected.length > 0) {
            res.send('添加成功');
        }
    });
});
//删除分类管理数据
router.post('/del', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql(`delete from Category where Id = ${req.query.id}`, (err, data) => {
        if (data.rowsAffected.length > 0) {
            res.send('删除成功');
        }
    });
});
//上传封面
router.all('/upload', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    if (req.file) {
        let filename = req.file.originalname;
        let oldPath = "./public/tmp/" + req.file.filename;
        let newPath = "./public/tmp/" + filename;
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                console.log(err);
                return
            }
        });
        let path = "http://" + req.headers.host + "/tmp/" + filename;
        res.send(path);
    } else {
        res.send("预检返回");
    }
})
//更新分类管理数据
router.post('/update', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql(`update Category set Cover='${req.query.coverUrl}' ,Name='${req.query.Name}' where Id = '${req.query.Id}'`, (err, data) => {
        if (data.rowsAffected.length > 0) {
            res.send('修改成功');
        }
    });
})
//更新封面
router.all('/updateImg', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    if (req.file) {
        let filename = req.file.originalname;
        let oldPath = "./public/tmp/" + req.file.filename;
        let newPath = "./public/tmp/" + filename;
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                console.log(err);
                return
            }
        });
        let path = "http://" + req.headers.host + "/tmp/" + filename;
        res.send(path);
    } else {
        res.send("预检返回");
    }
})

module.exports = router;